package com.rpc.demo.provider.rpc.server;

import com.rpc.demo.provider.rpc.server.handler.ServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

/**
 * @Author: ZhaoJie
 * @Date: 2022/4/6
 * @Description: RPC监听服务, 监听consumer远程调用的tcp连接
 * @Modify: ===================================================
 * Modifier        Modifytime        Description
 * ===================================================
 */

public class RpcServer {
    private static Logger logger = LoggerFactory.getLogger(RpcServer.class);

    private Map<String, Class> serviceMap;
    public RpcServer(Map<String, Class> serviceMap) {
        this.serviceMap = serviceMap;
    }

    /**
     * @author: zhaojie
     * @date: 2022/4/6
     * @description: 开始监听
     * @method: start
     * @param null
     * @class:  RpcServer
     * @return:
     */
    public void start(int port) {
        //监听端口，处理rpc请求
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            logger.info("RPC监听服务启动。。。");
            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(new ServerHandler(socket, serviceMap)).start();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}


